package coop.bancocredicoop.proyectos.gd.servlet;

import java.io.IOException;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.classic.Session;

import coop.bancocredicoop.proyectos.gd.Pager;
import coop.bancocredicoop.proyectos.gd.ServletUtils;
import coop.bancocredicoop.proyectos.gd.query.DataService;
import coop.bancocredicoop.proyectos.gd.reports.DocumentVersions;
import coop.bancocredicoop.proyectos.gd.reports.VersionsByFileReport;

public class ActualizacionesPorLegajo extends HttpServlet {

	private static final long serialVersionUID = 1L;
	
	private static final String actualizacionesPorLegajoJsp = "/jsp/actualizacionesPorLegajo/index.jsp";
	private static final Log log = LogFactory.getLog(ActualizacionesPorLegajo.class);
	
	@Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	
		int limit = 50;
		int offset = ServletUtils.getParameterAsInteger(request, "offset");
		Date dateFrom = ServletUtils.getParameterAsDate(request, "dateFrom", null);
		Date dateTo = ServletUtils.getParameterAsDate(request, "dateTo", null);
		String cajaId = ServletUtils.getParameterAsString(request, "cajaId");
		Long idPersona = ServletUtils.getParameterAsLong(request, "idPersona", null);
		String action = ServletUtils.getParameterAsString(request, "_action", "");
				
		if (action.equals("search")) {
			DataService dataService = new DataService();
			Session session = dataService.getSession();
			DocumentVersions documentVersions = null;
			try {
				VersionsByFileReport report = new VersionsByFileReport();
				documentVersions = report.versionsByFile(session, idPersona, cajaId, dateFrom, dateTo, offset, limit);
				Pager pager = new Pager(offset, limit, documentVersions.getTotalItems());
				
				request.setAttribute("dateFrom", ServletUtils.getMapFromDate(dateFrom));
				request.setAttribute("dateTo", ServletUtils.getMapFromDate(dateTo));
				request.setAttribute("documentVersions", documentVersions);
				request.setAttribute("pager", pager);
				
			} catch (Exception e) {
				log.error("Error in ActualizacionesPorLegajo report", e);
			} finally {
				dataService.closeSession(session);
			}
			
		}
		
		getServletContext().getRequestDispatcher(actualizacionesPorLegajoJsp).forward(request, response);
		
	}

}
